package com.yuju.controller.upload;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.yuju.common.Result;
import com.yuju.controller.base.BaseController;
import com.yuju.enums.ReturnCodeEnum;
import com.yuju.enums.ReturnStatusEnum;
import com.yuju.enums.SubSysEnum;
import com.yuju.model.upload.UploadFileModel;
import com.yuju.upload.enums.MultimediaReturnCodeEnum;
import com.yuju.upload.enums.UploadReturnCodeEnum;
import com.yuju.upload.model.MultimediaModel;
import com.yuju.upload.service.IMultimediaService;
import com.yuju.upload.service.IUploadService;
import com.yuju.util.Utils;
import com.yuju.vo.upload.UploadFileVO;

@Controller
@RequestMapping("upload")
public class UploadController extends BaseController<UploadFileVO, UploadFileModel> {
	private static final Logger logger = LoggerFactory.getLogger(BaseController.class);
	
	@Autowired
	private IUploadService uploadService;
	
	@Autowired
	private IMultimediaService multimediaService;
	
	@RequestMapping("file")
	public void uploadPic(@RequestParam("documentFile") MultipartFile pic, 
			HttpServletRequest request, HttpServletResponse response) {
		response.setContentType("application/json;charset=UTF-8");
		logger.debug("uploadPic start. fileName={}", null != pic ? pic.getOriginalFilename() : "");
		try {
			// 上传图片
			UploadFileVO vo = new UploadFileVO();
			vo.setPic(pic.getBytes());
			vo.setName(pic.getOriginalFilename());
			vo.setSize(pic.getSize());
			vo.setGroupId(request.getParameter("groupId"));
			vo.setHotelId(request.getParameter("hotelId"));
			vo.setHotelCode(request.getParameter("hotelCode"));
			vo.setEmpId(request.getParameter("empId"));
			vo.setEmpCode(request.getParameter("empCode"));
			vo.setEmpName(request.getParameter("empName"));
			try {
				vo.setResourceType(Byte.valueOf(request.getParameter("resourceType")));
			} catch(ClassCastException e) {
				e.printStackTrace();
			}
			try {
				vo.setChannelType(Byte.valueOf(request.getParameter("channelType")));
			} catch(ClassCastException e) {
				e.printStackTrace();
			} catch(NumberFormatException e) {
				e.printStackTrace();
			}
			vo.setTypeId(request.getParameter("typeId"));
			vo.setTypeName(request.getParameter("typeName"));
			vo.setDuration(request.getParameter("duration"));
			
			String path = uploadService.uploadPic(convert(vo));
			
			if (Utils.isNotNull(path)) {
				Date now = new Date();
				MultimediaModel multimediaModel = new MultimediaModel();
				multimediaModel.setId(Utils.getUUID());
				multimediaModel.setGroupId(vo.getGroupId());
				multimediaModel.setHotelId(vo.getHotelId());
				multimediaModel.setResourceUrl(path);
				multimediaModel.setFileName(vo.getName());
				multimediaModel.setFileSize(BigDecimal.valueOf(vo.getSize()));
				multimediaModel.setResourceType(vo.getResourceType());
				multimediaModel.setTypeId(vo.getTypeId());
				multimediaModel.setTypeName(vo.getTypeName());
				multimediaModel.setDuration(vo.getDuration());
				if (vo.getChannelType() != null) {
					multimediaModel.setChannelType(vo.getChannelType());
					multimediaModel.setChannelTypeName(SubSysEnum.getNameByValue(vo.getChannelType()));
				}
				multimediaModel.setCreateUserId(vo.getEmpId());
				multimediaModel.setCreateUserName(vo.getEmpName());
				multimediaModel.setUpdateUserId(vo.getEmpId());
				multimediaModel.setUpdateUserName(vo.getEmpName());
				multimediaModel.setGmtCreate(now);
				multimediaModel.setGmtModified(now);
				
				int rows = multimediaService.save(multimediaModel);

				Result result = new Result();
				if (rows == 0) {
					result.setStatus(ReturnStatusEnum.FAILURE.getCode());
					result.setMsg(ReturnStatusEnum.FAILURE.getDesc());
					result.setReturnCode(MultimediaReturnCodeEnum.MULTIMEDIA_SAVE_FALURE.getCode());
					result.setReturnMsg(MultimediaReturnCodeEnum.MULTIMEDIA_SAVE_FALURE.getDesc());

					response.getWriter().write(response(result));
					return ;
				}
			}
			
			// 回写图片
			/*JSONObject jsonObj = new JSONObject();
			if (Utils.isNotNull(path)) {
				jsonObj.put("url", url);
				jsonObj.put("isSuccess", true);
			} else {
				jsonObj.put("isSuccess", false);
				jsonObj.put("errorMsg", "上传图片失败！");
			}*/
			Result result = new Result();
			if (Utils.isNotNull(path)) {
				Map<String, Object> data = new HashMap<String, Object>();
				data.put("url", path);
				result.setData(data);
				result.setStatus(ReturnStatusEnum.SUCCESS.getCode());
				result.setMsg(ReturnStatusEnum.SUCCESS.getDesc());
				result.setReturnCode(UploadReturnCodeEnum.UPLOAD_SUCCESS.getCode());
				result.setReturnMsg(UploadReturnCodeEnum.UPLOAD_SUCCESS.getDesc());
			} else {
				result.setStatus(ReturnStatusEnum.FAILURE.getCode());
				result.setMsg(ReturnStatusEnum.FAILURE.getDesc());
				result.setReturnCode(UploadReturnCodeEnum.UPLOAD_FALURE.getCode());
				result.setReturnMsg(UploadReturnCodeEnum.UPLOAD_FALURE.getDesc());
			}
			
			response.getWriter().write(response(result));
		} catch(IOException e) {
			logger.debug("uploadPic io error:{}", e.getMessage(), e);
		}
		logger.debug("uploadPic end.");
	}
	
	@RequestMapping("delFile")
	@ResponseBody
	public Result delFile(@RequestBody JSONObject obj) {
		String path = obj.getString("path");
		int rows = uploadService.delFile(path);
		
		Result result = new Result();
		if (rows == 0) {
			rows = multimediaService.delByPath(path);
			
			if (rows > 0) {
				result.setStatus(ReturnStatusEnum.SUCCESS.getCode());
				result.setMsg(ReturnStatusEnum.SUCCESS.getDesc());
				result.setReturnCode(UploadReturnCodeEnum.FILE_DEL_SUCCESS.getCode());
				result.setReturnMsg(UploadReturnCodeEnum.FILE_DEL_SUCCESS.getDesc());
			} else {
				result.setStatus(ReturnStatusEnum.FAILURE.getCode());
				result.setMsg(ReturnStatusEnum.FAILURE.getDesc());
				result.setReturnCode(MultimediaReturnCodeEnum.MULTIMEDIA_DEL_FALURE.getCode());
				result.setReturnMsg(MultimediaReturnCodeEnum.MULTIMEDIA_DEL_FALURE.getDesc());
			}
		} else {
			result.setStatus(ReturnStatusEnum.FAILURE.getCode());
			result.setMsg(ReturnStatusEnum.FAILURE.getDesc());
			result.setReturnCode(UploadReturnCodeEnum.FILE_DEL_FALURE.getCode());
			result.setReturnMsg(UploadReturnCodeEnum.FILE_DEL_FALURE.getDesc());
		}
		
		return result;
	}
}
